#include <string.h>
#include "peripheral_iic.h"

/* Private variables ---------------------------------------------------------*/
I2C_HandleTypeDef I2cHandle;

void iic_init(){
	  /* I2C initialization */
  I2cHandle.Instance             = I2C1;                      /* I2C */
  I2cHandle.Init.ClockSpeed      = I2C_SPEEDCLOCK;            /* I2C communication speed */
  I2cHandle.Init.DutyCycle       = I2C_DUTYCYCLE;             /* I2C Duty cycle */
  I2cHandle.Init.OwnAddress1     = I2C_ADDRESS;               /* I2C address */
  I2cHandle.Init.AddressingMode  = I2C_ADDRESSINGMODE_7BIT;   /* 7-bit addressing mode */
  I2cHandle.Init.DualAddressMode = I2C_DUALADDRESS_DISABLE;   /* Disable dual address */
  /* I2cHandle.Init.OwnAddress2     = I2C_ADDRESS; */         /* Second address */
  I2cHandle.Init.GeneralCallMode = I2C_GENERALCALL_DISABLE;   /* Disable general call */
  I2cHandle.Init.NoStretchMode   = I2C_NOSTRETCH_DISABLE;     /* Enable clock stretching */
  if (HAL_I2C_Init(&I2cHandle) != HAL_OK)
  {
    APP_ErrorHandler();
  }
}

#define IIC_MEM_READ_WRONG
int8_t IIC_mem_read_bytes(uint8_t addr,  uint8_t *ch, uint16_t sizevalue)
{
	while (HAL_I2C_GetState(&I2cHandle) != HAL_I2C_STATE_READY);
	#ifdef IIC_MEM_READ_WRONG
	while (HAL_I2C_Master_Transmit_IT(&I2cHandle, AW86927_WRITE, &addr, 1) != HAL_OK)
  {
    APP_ErrorHandler();
  }
  while (HAL_I2C_GetState(&I2cHandle) != HAL_I2C_STATE_READY);
	while (HAL_I2C_Master_Receive_IT(&I2cHandle, AW86927_READ, (uint8_t *)ch, sizevalue) != HAL_OK)
  {
    APP_ErrorHandler();
  }
	#else
	while (HAL_I2C_Mem_Read_IT(&I2cHandle, AW86927_READ, addr, I2C_MEMADD_SIZE_8BIT, ch, sizevalue) != HAL_OK)
  {
    APP_ErrorHandler();
  }
	#endif
  while (HAL_I2C_GetState(&I2cHandle) != HAL_I2C_STATE_READY);
  /* Check the current I2C state */
	return 0;
}

uint8_t aTxBuffer[16], *p;
int8_t IIC_mem_write_bytes(uint8_t addr , uint8_t *ch, uint16_t sizevalue)
{
//	if(sizevalue <= 15){
//		aTxBuffer[0] = addr;
//		memcpy(&aTxBuffer[1], ch, sizevalue);
//		p = aTxBuffer;
//	}else{
//		ch[-1] = addr;
//		p = &ch[-1];
//	}
  while (HAL_I2C_GetState(&I2cHandle) != HAL_I2C_STATE_READY);
//	while (HAL_I2C_Master_Transmit_IT(&I2cHandle, AW86927_WRITE, p, sizevalue+1) != HAL_OK)
//  {
//    APP_ErrorHandler();
//  }
	while (HAL_I2C_Mem_Write_IT(&I2cHandle, AW86927_WRITE, addr, I2C_MEMADD_SIZE_8BIT, ch, sizevalue) != HAL_OK)
  {
    APP_ErrorHandler();
  }
  while (HAL_I2C_GetState(&I2cHandle) != HAL_I2C_STATE_READY);
	return 0;
  /* Check the current I2C state */
}
// AW8692X_REG_TMCFG AW869X_REG_TRIM_LRA
